package cn.ynrcb.personnelfile.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.ynrcb.personnelfile.admin.dao.NoticeDao;
import cn.ynrcb.personnelfile.admin.dao.NoticeSendDao;
import cn.ynrcb.personnelfile.admin.entity.NoticeEntity;
import cn.ynrcb.personnelfile.admin.entity.NoticeSendEntity;
import cn.ynrcb.personnelfile.admin.enums.NoticeTypeEnum;
import cn.ynrcb.personnelfile.admin.service.NoticeSendService;
import cn.ynrcb.personnelfile.admin.service.NoticeService;
import cn.ynrcb.personnelfile.admin.vo.NoticeListVo;
import cn.ynrcb.personnelfile.admin.vo.NoticeVo;
import cn.ynrcb.personnelfile.common.utils.BeanCopyUtil;
import cn.ynrcb.personnelfile.common.utils.EnumUtil;
import cn.ynrcb.personnelfile.common.utils.PageUtils;
import cn.ynrcb.personnelfile.sysadmin.service.CurrentUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("noticeService")
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, NoticeEntity> implements NoticeService {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private NoticeSendService noticeSendService;
    @Autowired
    private CurrentUserService currentUserService;
    @Autowired
    private NoticeSendDao noticeSendDao;
    @Autowired
    private NoticeDao noticeDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<NoticeListVo> page =
                new Page<NoticeListVo>(Convert.toLong(params.get("page"), 1L), Convert.toLong(params.get("limit"), 10L));
        List<NoticeListVo> list = baseMapper.queryListPage(page, params);
        page.setRecords(replaceList(list));
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageIndex(Map<String, Object> params) {
        Page<NoticeListVo> page =
                new Page<NoticeListVo>(Convert.toLong(params.get("page"), 1L), Convert.toLong(params.get("limit"), 5L));
        List<NoticeListVo> list = baseMapper.queryListPage(page, params);
        page.setRecords(replaceList(list));
        return new PageUtils(page);
    }

    @Override
    public List<NoticeEntity> queryList(Map<String, Object> params) {
        return baseMapper.queryList(params);
    }

    @Override
    public NoticeVo.InfoResp noticeInfo(Long noticeSendId) {

        return baseMapper.noticeInfo(noticeSendId);
    }

    @Transactional
    @Override
    public void saveNotice(NoticeVo.saveParam params) {
        NoticeEntity noticeEntity = new NoticeEntity();
        BeanCopyUtil.copyPropertiesIgnoreNull(params, noticeEntity);
        noticeEntity.setCreateUserId(currentUserService.getUserId());
        noticeService.save(noticeEntity);

        List<NoticeSendEntity> list = new ArrayList<>();
        List<String> userIdsList = Arrays.stream(params.getUserIds().split(",")).distinct().collect(Collectors.toList());
        userIdsList.forEach(e -> {
            NoticeSendEntity noticeSendEntity = new NoticeSendEntity();
            noticeSendEntity.setNoticeId(noticeEntity.getId());
            noticeSendEntity.setUserId(Convert.toLong(e));
            noticeSendEntity.setCreateUserId(currentUserService.getUserId());
            noticeSendEntity.setCreateTime(new Date());
            list.add(noticeSendEntity);
        });

        noticeSendService.saveBatch(list);
    }

    @Override
    public List<NoticeSendEntity> getCheckedTree(Integer id) {
        return noticeSendDao.getCheckedTree(id);
    }

    /**
     * 将返回数据中的枚举数据替换成枚举信息，可直接用于显示
     *
     * @param list
     * @return
     */
    public List<NoticeListVo> replaceList(List<NoticeListVo> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            for (NoticeListVo vo : list) {
                vo.setTypeName(EnumUtil.getByCode(NoticeTypeEnum.class,vo.getType()).getMessage());
            }
        }
        return list;
    }

//    @Override
//    public void adminSaveNotice(NoticeEntity notice) {
//        notice.setCreateTime(new Date());
//        noticeDao.insert(notice);
//        saveNoticeSend(notice, notice.getUserIds());
//    }

    private void saveNoticeSend(NoticeEntity noticeEntity, String userIds) {
        if (userIds != null ) {
            String[] userIdsArr = userIds.split(",");
            for (String userId : userIdsArr) {
                NoticeSendEntity noticeSendEntity = new NoticeSendEntity();
                noticeSendEntity.setNoticeId(noticeEntity.getId());
                noticeSendEntity.setUserId(Long.parseLong(userId));
                noticeSendEntity.setCreateTime(new Date());
                noticeSendDao.insert(noticeSendEntity);
            }
        }
    }

    @Override
    public void updateNoticeById(NoticeEntity notice) {
        noticeDao.updateById(notice);
        noticeSendDao.deleteByNoticeId(notice.getId());
        saveNoticeSend(notice, notice.getUserIds());
    }

    @Override
    public PageUtils queryAdminPage(Map<String, Object> params) {
        Page<NoticeEntity> page = new Page<NoticeEntity>(Long.valueOf(params.get("page")+""), Long.valueOf(params.get("limit")+""));
        List<NoticeEntity> list = baseMapper.queryAdminPage(page, params);
        page.setRecords(list);
        return new PageUtils((IPage<?>) page);
    }

    @Override
    public PageUtils queryMyNoticePage(Map<String, Object> params) {
        Page<NoticeSendEntity> page = new Page<NoticeSendEntity>(Long.valueOf(params.get("page")+""), Long.valueOf(params.get("limit")+""));
        List<NoticeSendEntity> list = noticeSendDao.queryPage(page, params);
        page.setRecords(list);
        return new PageUtils((IPage<?>) page);
    }
}
